from flask import Blueprint, request,jsonify
from db import db
import json
from utils.comm import gain_data,qntoken
import os

upload_file = Blueprint('app2',__name__)

# 获取token
@upload_file.route('/get_token')
def get_token():
    token = qntoken()
    return jsonify({'code':200,'token':token})

# 上传视频
@upload_file.route('/vedioUpload',methods=['POST'])
def vedioUpload():
    #获取要上传的文件流，课程id
    file = request.files['file']
    print("****************")
    print(file)
    course_id = request.form['id']
    #判断文件夹是否存在，如果没有，创建文件夹
    path = './upload/'+str(course_id)
    if not os.path.exists(path):
        os.mkdir(path)
    #上传文件到指定文件夹
    file.save(os.path.join(path,file.filename))
    #返回结果
    return jsonify({"code":200,'url':path+'/'+file.filename})

# 添加章节
@upload_file.route('/jie',methods = ['POST','GET'])
def jie():
    if request.method=='POST':
        gain = request.data
        if gain:
            gain = json.loads(gain)
        else:
            gain = request.form
        print("*************")
        print(gain)
        sql = """
            insert into jie values(0,'%s',%d,'%s')
        """%(gain['name'],gain['course_id'],gain['video_url'])
        res = db.insert(sql)
        return jsonify({'code':200})
    else:
        sql = """
            select id,title from courses
        """
        res = db.findall(sql)
        return jsonify({'code':200,'matter':res})

# 展示章节
@upload_file.route('/show_jie')
def show_jie():
    sql = """
        select *from jie
    """
    res = db.findall(sql)
    return jsonify({'code':200,'matter':res})
